package com.comprehensive.personalfile.controller;

import com.comprehensive.common.dto.FolderFlieInfo;
import com.comprehensive.common.dto.PageResponse;
import com.comprehensive.common.po.FileInfo;
import com.comprehensive.personalfile.service.FileService;
import jakarta.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/file")
public class FileController {

    private final FileService fileService;

    @Autowired
    public FileController(FileService fileService) {
        this.fileService = fileService;
    }

    /**
     * 上传文件分片
     */
    @PostMapping("/uploadChunk")
    public ResponseEntity<FileInfo> uploadChunk(
            @RequestParam String uploadId,
            @RequestParam int chunkIndex,
            @RequestParam int totalChunks,
            @RequestParam String fileName,
            @RequestPart("chunkFile") MultipartFile chunkFile) {
        try {
            FileInfo fileInfo = fileService.uploadChunk(uploadId, chunkIndex, totalChunks, fileName, chunkFile);
            return ResponseEntity.status(HttpStatus.CREATED).body(fileInfo);
        } catch (IOException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
        }
    }

    /**
     * 合并文件分片
     */
    @PostMapping("/mergeChunks")
    public ResponseEntity<FileInfo> mergeChunks(
            @RequestParam String uploadId,
            @RequestParam String fileName) {
        try {
            FileInfo fileInfo = fileService.mergeChunks(uploadId, fileName);
            return ResponseEntity.ok(fileInfo);
        } catch (FileNotFoundException e) {
            return ResponseEntity.notFound().build();
        } catch (IOException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
        }
    }

    /**
     * 查询已上传的分片索引
     */
    @GetMapping("/uploadedChunks")
    public ResponseEntity<List<Integer>> getUploadedChunks(
            @RequestParam String uploadId,
            @RequestParam String fileName) {
        try {
            List<Integer> uploadedIndices = fileService.getUploadedChunks(uploadId, fileName);
            return ResponseEntity.ok(uploadedIndices);
        } catch (IOException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
        }
    }

    /**
     * 获取文件信息列表-分页查询
     */
    @GetMapping("/listPage")
    public ResponseEntity<PageResponse>listPage(@RequestParam(defaultValue = "1") int pageNum,
                                                @RequestParam(defaultValue = "10") int pageSize){
        PageResponse<FileInfo> fileInfoPageResponse = fileService.listPage(pageNum, pageSize);
        return ResponseEntity.ok(fileInfoPageResponse);

    }

    /**
     * 文件上传接口
     */
    @PostMapping("/upload")
    public ResponseEntity<FileInfo> uploadFile(@RequestParam("file") MultipartFile file) {
        try {
            FileInfo fileInfo = fileService.uploadFile(file);
            return ResponseEntity.status(HttpStatus.CREATED).body(fileInfo);
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
            return ResponseEntity.badRequest().body(null);
        } catch (IOException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
        }
    }

    /**
     * 文件下载接口
     */
    @GetMapping("/download/{fileId}")
    public void downloadFile(@PathVariable String fileId, HttpServletResponse response) {
        try {
            fileService.downloadFile(fileId, response);
        } catch (IOException e) {
            try {
                response.sendError(HttpStatus.INTERNAL_SERVER_ERROR.value(), "文件下载失败");
            } catch (IOException ex) {
            }
        }
    }

    /**
     * 列出目录下的文件信息
     */
    @GetMapping("/list")
    public ResponseEntity<List<FolderFlieInfo>> listFiles(@RequestParam String directoryPath) {
        try {
            List<FolderFlieInfo> fileInfos = fileService.listFiles(directoryPath);
            return ResponseEntity.ok(fileInfos);
        } catch (FileNotFoundException e) {
            return ResponseEntity.notFound().build();
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().body(null);
        } catch (IOException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
        }
    }

    /**
     * 流式读取文件内容
     */
    @GetMapping("/stream")
    public ResponseEntity<InputStreamResource> streamFile(@RequestParam String filePath) {
        try {
            InputStream inputStream = fileService.readFileAsStream(filePath);
            InputStreamResource resource = new InputStreamResource(inputStream);
            File file = new File(filePath);
            return ResponseEntity.ok()
                    .contentType(MediaType.APPLICATION_OCTET_STREAM)
                    .header(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"" + file.getName() + "\"")
                    .body(resource);
        } catch (FileNotFoundException e) {
            return ResponseEntity.notFound().build();
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().body(null);
        } catch (IOException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
        }
    }
    /**
     * 获取 Markdown 文件内容
     */
    @GetMapping("/markdown/content")
    public ResponseEntity<String> getMarkdownContent(@RequestParam String filePath) {
        try {
            String content = fileService.getMarkdownContent(filePath);
            return ResponseEntity.ok(content);
        } catch (FileNotFoundException e) {
            return ResponseEntity.notFound().build();
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().body(null);
        } catch (IOException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
        }
    }

    /**
     * 保存 Markdown 内容到文件
     */
    @PostMapping("/markdown/save")
    public ResponseEntity<Void> saveMarkdownContent(@RequestParam String filePath, @RequestBody String content) {
        try {
            fileService.saveMarkdownContent(filePath, content);
            return ResponseEntity.ok().build();
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().build();
        } catch (IOException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    /**
     * 解析磁力链接，获取包含的文件信息
     */
   @GetMapping("/magnetLinkInfo")
   public ResponseEntity<Map> getMagnetLinkInfoByUrl(@RequestParam String magnetLink){
       Map<String, Object> magnetLinkInfo = fileService.getMagnetLinkInfoByUrl(magnetLink);
       return ResponseEntity.ok(magnetLinkInfo);
   }
    /**
     * 下载磁力链接
     */
    @GetMapping("/downloadMagnetLink")
    public ResponseEntity<Void> downloadMagnetLink(@RequestParam String magnetLink,@RequestParam int selectDownloadIndex){
       try {
           fileService.downloadMagnetLink(magnetLink,selectDownloadIndex);
           return ResponseEntity.ok().build();
       } catch (Exception e) {
           return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
       }
    }

}